package 栈;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Stack;

/**
 * https://leetcode-cn.com/problems/score-of-parentheses/
 */
public class _856_括号的分数 {
    /*
    借鉴别人的 (()(())) = (()) + ((())) , 且  分数 = 2^(层数-1)
    出现 '(' 代表层数+1 ， 出现 ')' 代表层数 -1
    */
    public int scoreOfParentheses(String S) {
        int ans = 0, deep = 0;
        for (int i = 0; i < S.length(); i++) {
            char c = S.charAt(i);
            if ('(' == c) deep++;
            else deep--;
            if (c == ')' && S.charAt(i - 1) == '(') ans += 1 << deep;

        }
        return ans;
    }

    /**
     *用栈实现
     * https://leetcode-cn.com/problems/score-of-parentheses/solution/gua-hao-de-fen-shu-by-leetcode/
     * @param S
     * @return
     */
    public int scoreOfParentheses1(String S) {
        Stack<Integer> stack = new Stack<>();
        stack.push(0); // The score of the current frame
        for (int i = 0; i < S.length(); i++) {
            char c = S.charAt(i);
            if (c == '(') {
                stack.push(0);
            } else {
                int b1 = stack.pop();
                int b2 = stack.pop();
                stack.push(b2 + Math.max(b1 * 2, 1));
            }
        }
        return stack.pop();
    }
}
